import React, { useState } from 'react';
import { Routes, Route, Link, useLocation } from 'react-router-dom';
import { Search, Filter, Download, Plus, Star, Clock, User, Mail, Phone, MapPin, Award, AlertCircle, CheckCircle2 } from 'lucide-react';
import CandidateDetail from './CandidateDetail';
import { WithPermission } from './withPermission';

interface Candidate {
  id: string;
  name: string;
  email: string;
  phone: string;
  position: string;
  location: string;
  stage: string;
  score: number;
  avatar: string;
  skills: string[];
  experience: string;
  education: string;
  updatedAt: string;
  highlights: string[];
  concerns: string[];
}

const mockCandidates: Candidate[] = [
  {
    id: '1',
    name: '张三',
    email: 'zhang@example.com',
    phone: '+86 138-0013-8000',
    position: '前端工程师',
    location: '上海',
    stage: '初筛',
    score: 85,
    avatar: 'https://images.pexels.com/photos/2379004/pexels-photo-2379004.jpeg?auto=compress&cs=tinysrgb&w=32&h=32&fit=crop&crop=face',
    skills: ['React', 'TypeScript', 'Node.js'],
    experience: '3年',
    education: '本科',
    updatedAt: '2小时前',
    highlights: ['React经验丰富', 'TypeScript熟练', '有大型项目经验'],
    concerns: ['Node.js经验较少']
  },
  {
    id: '2',
    name: '李四',
    email: 'li@example.com',
    phone: '+86 138-0013-8001',
    position: 'Java工程师',
    location: '北京',
    stage: '面试',
    score: 78,
    avatar: 'https://images.pexels.com/photos/1222271/pexels-photo-1222271.jpeg?auto=compress&cs=tinysrgb&w=32&h=32&fit=crop&crop=face',
    skills: ['Java', 'Spring Boot', 'MySQL'],
    experience: '5年',
    education: '硕士',
    updatedAt: '1天前',
    highlights: ['Spring Boot专家', '数据库设计能力强'],
    concerns: ['缺少微服务经验', '项目管理经验不足']
  },
  {
    id: '3',
    name: '王五',
    email: 'wang@example.com',
    phone: '+86 138-0013-8002',
    position: 'UI设计师',
    location: '深圳',
    stage: 'Offer',
    score: 92,
    avatar: 'https://images.pexels.com/photos/1239291/pexels-photo-1239291.jpeg?auto=compress&cs=tinysrgb&w=32&h=32&fit=crop&crop=face',
    skills: ['Figma', 'Sketch', 'Prototype'],
    experience: '4年',
    education: '本科',
    updatedAt: '3天前',
    highlights: ['设计理念先进', '用户体验专业', '作品集优秀'],
    concerns: []
  }
];

export default function Candidates() {
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedStage, setSelectedStage] = useState('');
  const [selectedScore, setSelectedScore] = useState('');
  const location = useLocation();

  const isDetailView = location.pathname.includes('/detail/');

  const stages = ['初筛', '面试', 'Offer', '已入职', '已拒绝'];
  const scoreRanges = ['90+', '80-89', '70-79', '60-69', '<60'];

  const filteredCandidates = mockCandidates.filter(candidate => {
    const matchesSearch = candidate.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         candidate.position.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         candidate.skills.some(skill => skill.toLowerCase().includes(searchTerm.toLowerCase()));
    
    const matchesStage = !selectedStage || candidate.stage === selectedStage;
    
    const matchesScore = !selectedScore || (() => {
      const score = candidate.score;
      switch (selectedScore) {
        case '90+': return score >= 90;
        case '80-89': return score >= 80 && score < 90;
        case '70-79': return score >= 70 && score < 80;
        case '60-69': return score >= 60 && score < 70;
        case '<60': return score < 60;
        default: return true;
      }
    })();
    
    return matchesSearch && matchesStage && matchesScore;
  });

  const getScoreColor = (score: number) => {
    if (score >= 90) return 'text-green-600 bg-green-50';
    if (score >= 80) return 'text-blue-600 bg-blue-50';
    if (score >= 70) return 'text-yellow-600 bg-yellow-50';
    return 'text-red-600 bg-red-50';
  };

  const getStageColor = (stage: string) => {
    switch (stage) {
      case '初筛': return 'bg-gray-100 text-gray-800';
      case '面试': return 'bg-blue-100 text-blue-800';
      case 'Offer': return 'bg-green-100 text-green-800';
      case '已入职': return 'bg-purple-100 text-purple-800';
      case '已拒绝': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  };

  if (isDetailView) {
    return (
      <Routes>
        <Route path="detail/:id" element={<CandidateDetail />} />
      </Routes>
    );
  }

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      {/* Header */}
      <div className="sm:flex sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">候选人</h1>
          <p className="mt-2 text-sm text-gray-700">
            管理和评估求职候选人
          </p>
        </div>
        <div className="mt-4 sm:mt-0">
          <WithPermission allow={["hr", "boss"]} disabledFallback={
            <button className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-lg text-white bg-gray-300 cursor-not-allowed" disabled>
              <Plus className="h-4 w-4 mr-2" />
              新建候选人
            </button>
          }>
            <button className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-lg text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 transition-colors">
              <Plus className="h-4 w-4 mr-2" />
              新建候选人
            </button>
          </WithPermission>
        </div>
      </div>

      {/* Filters */}
      <div className="mt-6 bg-white rounded-lg shadow-sm border border-gray-200 p-4">
        <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-3 h-4 w-4 text-gray-400" />
            <input
              type="text"
              placeholder="搜索姓名、岗位、技能..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-9 w-full border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <select
            value={selectedStage}
            onChange={(e) => setSelectedStage(e.target.value)}
            className="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">所有阶段</option>
            {stages.map(stage => (
              <option key={stage} value={stage}>{stage}</option>
            ))}
          </select>
          
          <select
            value={selectedScore}
            onChange={(e) => setSelectedScore(e.target.value)}
            className="border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          >
            <option value="">所有评分</option>
            {scoreRanges.map(range => (
              <option key={range} value={range}>{range}分</option>
            ))}
          </select>
          
          <div className="flex space-x-2">
            <button className="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50">
              <Filter className="h-4 w-4 mr-2" />
              更多筛选
            </button>
            <button className="inline-flex items-center px-3 py-2 border border-gray-300 text-sm font-medium rounded-lg text-gray-700 bg-white hover:bg-gray-50">
              <Download className="h-4 w-4 mr-2" />
              导出
            </button>
          </div>
        </div>
      </div>

      {/* Results count */}
      <div className="mt-4 text-sm text-gray-500">
        找到 {filteredCandidates.length} 位候选人
      </div>

      {/* Candidates list */}
      <div className="mt-6 bg-white shadow-sm rounded-lg overflow-hidden">
        <div className="divide-y divide-gray-200">
          {filteredCandidates.map((candidate) => (
            <Link key={candidate.id} to={`detail/${candidate.id}`}>
              <div className="p-6 hover:bg-gray-50 transition-colors cursor-pointer">
                <div className="flex items-center justify-between">
                  <div className="flex items-center space-x-4">
                    <img
                      className="h-12 w-12 rounded-full"
                      src={candidate.avatar}
                      alt={candidate.name}
                    />
                    <div>
                      <h3 className="text-lg font-medium text-gray-900">{candidate.name}</h3>
                      <p className="text-sm text-gray-500">应聘：{candidate.position}</p>
                    </div>
                  </div>
                  
                  <div className="flex items-center space-x-6">
                    {/* Score */}
                    <div className="text-center">
                      <div className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium ${getScoreColor(candidate.score)}`}>
                        <Award className="h-3 w-3 mr-1" />
                        {candidate.score}分
                      </div>
                      <p className="text-xs text-gray-500 mt-1">匹配评分</p>
                    </div>
                    
                    {/* Stage */}
                    <div className="text-center">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium ${getStageColor(candidate.stage)}`}>
                        {candidate.stage}
                      </span>
                      <p className="text-xs text-gray-500 mt-1">当前阶段</p>
                    </div>
                    
                    {/* Updated time */}
                    <div className="text-center">
                      <div className="flex items-center text-sm text-gray-500">
                        <Clock className="h-3 w-3 mr-1" />
                        {candidate.updatedAt}
                      </div>
                      <p className="text-xs text-gray-500 mt-1">最后更新</p>
                    </div>
                  </div>
                </div>
                
                {/* Additional info */}
                <div className="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
                  <div className="flex items-center text-sm text-gray-500">
                    <Mail className="h-4 w-4 mr-2" />
                    {candidate.email}
                  </div>
                  <div className="flex items-center text-sm text-gray-500">
                    <Phone className="h-4 w-4 mr-2" />
                    {candidate.phone}
                  </div>
                  <div className="flex items-center text-sm text-gray-500">
                    <MapPin className="h-4 w-4 mr-2" />
                    {candidate.location} • {candidate.experience}经验
                  </div>
                </div>
                
                {/* Skills */}
                <div className="mt-3 flex flex-wrap gap-2">
                  {candidate.skills.map((skill, index) => (
                    <span key={index} className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                      {skill}
                    </span>
                  ))}
                </div>
                
                {/* Highlights and concerns */}
                {(candidate.highlights.length > 0 || candidate.concerns.length > 0) && (
                  <div className="mt-4 flex items-center space-x-4">
                    {candidate.highlights.length > 0 && (
                      <div className="flex items-center text-sm">
                        <CheckCircle2 className="h-4 w-4 text-green-500 mr-1" />
                        <span className="text-green-700">{candidate.highlights.length} 个亮点</span>
                      </div>
                    )}
                    {candidate.concerns.length > 0 && (
                      <div className="flex items-center text-sm">
                        <AlertCircle className="h-4 w-4 text-yellow-500 mr-1" />
                        <span className="text-yellow-700">{candidate.concerns.length} 个关注点</span>
                      </div>
                    )}
                  </div>
                )}
              </div>
            </Link>
          ))}
        </div>
      </div>
    </div>
  );
}